package com.baidu.lib_common.utils

import android.content.pm.PackageManager
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import java.lang.ref.WeakReference


class PermissionsUtils private constructor(){
    private var mWeakActivity: WeakReference<AppCompatActivity>? = null
    private var launcher: ActivityResultLauncher<String>? = null
    private var callback: ()->Unit = {}
    companion object{
        val instance = PermissionsUtils()
    }
    fun initPermissionsUtils(activity: AppCompatActivity){
        mWeakActivity = WeakReference(activity)
        launcher = activity.registerForActivityResult(
            ActivityResultContracts.RequestPermission(),
            {
                if(it){
                    callback
                }else{
                    Toast.makeText(activity,"请授权以正常使用应用",Toast.LENGTH_SHORT).show()
                }
            }
        )
    }
    fun initCallback(callback: ()->Unit){
        this.callback = callback
    }
    fun checkPermission(permission: String): Boolean{
        val result = mWeakActivity!!.get()!!.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
        return result
    }
    fun requestPermission(permission: String){
        launcher!!.launch(permission)
    }
}